package com.wxw.uploadvsftp.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.wxw.uploadvsftp.utils.FtpUtil;
import com.wxw.uploadvsftp.utils.IDUtils;
import com.wxw.uploadvsftp.utils.QrCodeUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author wxw
 * @data 2021/11/26 21 :42
 * @description
 */
@RestController
public class FileContrller {
    @Value("${FTP.ADDRESS}")
    private String host;
    // 端口
    @Value("${FTP.PORT}")
    private int port;
    // ftp用户名
    @Value("${FTP.USERNAME}")
    private String userName;
    // ftp用户密码
    @Value("${FTP.PASSWORD}")
    private String passWord;
    // 文件在服务器端保存的主目录
    @Value("${FTP.BASEPATH}")
    private String basePath;
    // 访问图片时的基础url
    @Value("${FTP.URL}")
    private String baseUrl;

    @PostMapping("/pic/upload")
    @ResponseBody
    public String pictureUpload(
            @RequestParam("pic") MultipartFile[] uploadFile) {
        String filePaths= "";
        for (MultipartFile file : uploadFile) {
            try {
                //1、给上传的图片生成新的文件名
                //1.1获取原始文件名
                String oldName = file.getOriginalFilename();
                //1.2使用IDUtils工具类生成新的文件名，新文件名 = newName + 文件后缀
                String newName = IDUtils.genImageName();
                newName = newName + oldName.substring(oldName.lastIndexOf("."));
                //1.3生成文件在服务器端存储的子目录
                SimpleDateFormat DateFormat = new SimpleDateFormat("/yyyy/MM/dd");
                String filePath = DateFormat.format(new Date());

                //3、把图片上传到图片服务器
                //3.1获取上传的io流
                InputStream input = file.getInputStream();

                //3.2调用FtpUtil工具类进行上传
                boolean result = FtpUtil.uploadFile(host, port, userName, passWord, basePath, filePath, newName, input);

                if(result) {
                    if (Objects.equals("",filePaths)){
                        filePaths= baseUrl+filePath+"/"+newName;
                    }else {
                        filePaths+=";"+baseUrl+filePath+"/"+newName;
                    }
                }else {
                    return "false";
                }
            } catch (IOException e) {
                return "false";
            }
        }

        return  filePaths;
}

    @PostMapping("getQrCodeFtp")
    public String getQrCodeFtp() throws IOException, WriterException {


        String text = "施工单位：";
        //解决中文乱码
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 300, 300, hints);

        BufferedImage image = QrCodeUtil.deleteWhite(bitMatrix);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //输出图像
        ImageIO.write(image, "png", outputStream);
        InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        //3.2调用FtpUtil工具类进行上传
        SimpleDateFormat DateFormat = new SimpleDateFormat("/yyyy/MM/dd");
        String filePath = DateFormat.format(new Date());
        boolean result = FtpUtil.uploadFile(host, port, userName, passWord, basePath, filePath, "12345.png",inputStream);
       return  baseUrl+filePath+"/"+"12345.png";
    }
    @PostMapping("getQrCode")
    public String getQrCode(HttpServletRequest request) throws IOException, WriterException {
        String realPath=request.getSession().getServletContext().getRealPath("/uploadFile/");
        File directory=new File(realPath);
        if (!directory.exists()){
            directory.mkdirs();
        }
        String newPath=realPath+"12345.png";
        String text = "二维码信息：";
        //输出图像
        QrCodeUtil.generateQRCodeImage(text, newPath ,300, 300,true);
        return  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/uploadFile/12345.png";
    }

}
